<script lang="ts" setup>
import type { FormInstance, DrawerProps } from 'ant-design-vue';
import { $t } from '@vben/locales';
import type { CodelabsAlgorithm } from './types';
import { onMounted, reactive, ref, watch, computed, toRefs } from 'vue';
import { message } from 'ant-design-vue';
import { removeEmpty, removeNull } from '#/utils/common';
import ImageUpload from '#/components/ImageUpload.vue';
import { useDebounceFn } from '@vueuse/core';
import dayjs, { Dayjs } from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import type { ComponentSetting } from '../../uctoo/component_setting/types.ts';
import { uctoo_codelabs_algorithm, uctoo_component_setting } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
import { VbenIcon } from '@vben-core/shadcn-ui';

// 加载 utc 和 timezone 插件
dayjs.extend(utc);
dayjs.extend(timezone);
const loading = ref(false);

const props = defineProps<{
  mode: 'add' | 'edit';
  record: CodelabsAlgorithm | null;
  visible: boolean;
  componentSettingData: ComponentSetting[];
  ids?:(string[] | number[]);
}>();

// 计算属性判断空值
const isIdsEmpty = computed(() => 
  !props.ids || props.ids.length === 0
);

const emit = defineEmits(['update:visible', 'success']);

const ENTITY_PROXY: { [K in keyof CodelabsAlgorithm]: null } = {
id: null,
command_name: null,
algorithm_code: null,
filename: null,
filepath: null,
template_url: null,
opensource: null,
author: null,
author_url: null,
user_id: null,
tags: null,
docs: null,
images: null,
description: null,
price: null,
status: null,
arguments: null,
creator: null,
created_at: null,
updated_at: null,
deleted_at: null,
};
 
// 获取有效字段选项
const getFieldOptions = () => {
  // 排除系统字段
  const EXCLUDED_FIELDS = ['id', 'creator', 'created_at', 'updated_at', 'deleted_at'] as const;
  
  return (Object.keys(ENTITY_PROXY) as Array<keyof CodelabsAlgorithm>).filter(
    field => !EXCLUDED_FIELDS.includes(field as typeof EXCLUDED_FIELDS[number])
  );
};
const formRef = ref<FormInstance>();


const formState = reactive<Record<keyof CodelabsAlgorithm, any>>(
  Object.fromEntries(
    getFieldOptions().map(k => [k, '']) // 初始化所有有效字段
  ) as Record<keyof CodelabsAlgorithm, any>
);
     // 用户选择的表单项，初始化为表单所有项或根据需求预选一些项
    const selectedFormItems = ref<Array<keyof CodelabsAlgorithm>>(Object.keys(formState) as Array<keyof CodelabsAlgorithm>);
    const handleFormItemChange = () => {
      console.log('Selected columns:', selectedFormItems.value);
    }; 

/** rules */
const rules = {
 command_name: [{message: $t('page.Required'), required: true}],
 algorithm_code: [{message: $t('page.Required'), required: false}],
 filename: [{message: $t('page.Required'), required: false}],
 filepath: [{message: $t('page.Required'), required: false}],
 template_url: [{message: $t('page.Required'), required: false}],
 opensource: [{message: $t('page.Required'), required: false}],
 author: [{message: $t('page.Required'), required: false}],
 author_url: [{message: $t('page.Required'), required: false}],
 user_id: [{message: $t('page.Required'), required: false}],
 tags: [{message: $t('page.Required'), required: false}],
 docs: [{message: $t('page.Required'), required: false}],
 images: [{message: $t('page.Required'), required: false}],
 description: [{message: $t('page.Required'), required: false}],
 price: [{message: $t('page.Required'), required: false}],
 status: [{message: $t('page.Required'), required: false}],
 arguments: [{message: $t('page.Required'), required: false}],
};


watch(
  () => props.record,
  (newVal) => {
    if (newVal) {
      Object.assign(formState, newVal);
    } else {
      Object.keys(formState).forEach((key) => {
        formState[key as keyof CodelabsAlgorithm] = '';
      });
    }

    if(props.componentSettingData[0]){
      selectedFormItems.value = JSON.parse(props.componentSettingData[0].selected_form_column ?? '[]');
    }
  },
  { immediate: true },
);

const handleOk = () => {
  if(isIdsEmpty.value){ //单条数据编辑提交
  console.log(formState);
    interface Formated {
      id?:string,
      command_name?: string,
      algorithm_code?: string,
      filename?: string,
      filepath?: string,
      template_url?: string,
      opensource?: number,
      author?: string,
      author_url?: string,
      user_id?: string,
      tags?: string,
      docs?: string,
      images?: string,
      description?: string,
      price?: number,
      status?: number,
      arguments?: string,
     };

    const formatedFormState: Formated = {
      id: formState.id,
      command_name: formState.command_name,
      algorithm_code: formState.algorithm_code,
      filename: formState.filename,
      filepath: formState.filepath,
      template_url: formState.template_url,
      opensource: Number(formState.opensource),
      author: formState.author,
      author_url: formState.author_url,
      user_id: formState.user_id,
      tags: formState.tags,
      docs: formState.docs,
      images: formState.images,
      description: formState.description,
      price: Number(formState.price),
      status: Number(formState.status),
      arguments: formState.arguments,
     };

  formRef.value?.validate().then(async () => {
    try {
      if (props.mode === 'add') {
        delete formatedFormState['id'];
        await useAxiosRepo(uctoo_codelabs_algorithm).api().adductooCodelabsAlgorithm(removeEmpty(formatedFormState));
        message.success($t('page.AddSuccess'));
      } else {
        await useAxiosRepo(uctoo_codelabs_algorithm).api().edituctooCodelabsAlgorithm(removeNull(formatedFormState));
          message.success($t('page.EditSuccess'));        
      }
      emit('success');
    } catch {
      message.error($t('page.EditFailed'));
    }
  });
  }else{ //多条数据编辑提交
    handleSubmit();
  }
  
};

const placement = ref<DrawerProps['placement']>('left');
const open = ref<boolean>(false);
const handleCancel = () => {
  emit('update:visible', false);
};

const showDrawer = () => {
  open.value = true;
};

const onClose = () => {
  open.value = false;
};

const onSetting = async () => {
  try {
      if(props.componentSettingData[0]){
        props.componentSettingData[0].selected_form_column = JSON.stringify(selectedFormItems.value);
      }
      await useAxiosRepo(uctoo_component_setting).api().edituctooComponentSetting(removeEmpty(props.componentSettingData[0]));
        message.success($t('page.SaveSuccess'));
    } catch {
      message.error($t('page.EditFailed'));
    }
  open.value = false;
};

// 动态表单项
interface FormField {
  selectedField?: keyof CodelabsAlgorithm;
  inputValue: string | number;
}

// 响应式表单数据
const formFields = reactive<FormField[]>(
  Array.from({ length: 1 }, () => ({
    selectedField: undefined,
    inputValue: ''
  }))
);

// 添加表单项
const addField = () => {
  formFields.push({ selectedField: undefined, inputValue: '' });
};

const removeField = (index: number) => {
  if (formFields.length > 1) {
    formFields.splice(index, 1);
  }
};

// 处理字段选择变化
const handleFieldChange = (index: number, value: keyof CodelabsAlgorithm) => {
  // 检查是否已存在相同字段
  const isDuplicate = formFields.some(
    (f, i) => i !== index && f.selectedField === value
  );  
  if (isDuplicate) {
    message.error($t('page.DuplicateSeletedField'));
    return;
  }

  const currentField = formFields[index];
  if (!currentField) return;
  // 清除旧字段的关联状态
  if (currentField.selectedField) {
    delete formState[currentField.selectedField];
  }
  // 更新字段并初始化值
  currentField.selectedField = value;
  currentField.inputValue = isNumberField(value) ? 0 : '';
  // 更新表单状态
  formState[value] = currentField.inputValue;
};

const isNumberField = (field: keyof CodelabsAlgorithm): boolean => {
  const NUMBER_FIELDS: (keyof CodelabsAlgorithm)[] = ['opensource','price','status',];
  return NUMBER_FIELDS.includes(field);
};

const handleSubmit = async () => {
  // 显式遍历输入组件值并同步到 formFields
  formFields.forEach((field, index) => {
    const inputElement = document.querySelector(`#input-${index}`) as HTMLInputElement;
    if (inputElement) {
      field.inputValue = isNumberField(field.selectedField!) 
        ? Number(inputElement.value) 
        : inputElement.value;
    }
  });
  
    // 转换为目标数据结构
    const formData = formFields.reduce((acc, field) => {
    if (field.selectedField && field.inputValue !== undefined) {
      // 数字字段类型转换
      acc[field.selectedField] = isNumberField(field.selectedField) 
        ? Number(field.inputValue) 
        : field.inputValue;
    }
    return acc;
  }, {} as Record<keyof CodelabsAlgorithm, any>);
    //ids加入到最终提交数据
  const submitData = {
    ...formData,          // 保留原有字段
     ids: JSON.stringify(props.ids) // 新增序列化后的 ids 字段
  };

  await useAxiosRepo(uctoo_codelabs_algorithm).api().edituctooCodelabsAlgorithm(JSON.parse(JSON.stringify(submitData)));
  message.success($t('page.EditSuccess'));
  emit('success'); 
};

onMounted(() => {
});
</script>

<template>
  <a-modal
    :open="visible"
    :title="mode === 'add' ? $t('page.Add') : $t('page.Edit')"
    @cancel="handleCancel"
    @ok="handleOk"
  >
  <template #footer>
        <a-button type="primary" @click="showDrawer">{{$t('page.Setting')}}</a-button>
        <a-button key="back" @click="handleCancel">{{$t('page.Cancel')}}</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">{{$t('page.Submit')}}</a-button>
      </template> <!-- -->
  <a-drawer :width="500" title="" :placement="placement" :open="open" @close="onClose">
    <template #extra>
      <a-button style="margin-right: 8px" @click="onClose">{{$t('page.Cancel')}}</a-button>
      <a-button type="primary" @click="onSetting">{{$t('page.Submit')}}</a-button>
    </template>
    <a-checkbox-group v-model:value="selectedFormItems" @change="handleFormItemChange">
      <a-checkbox v-for="(value, key) in formState" :key="key" :value="key" >
        {{ $t(`database_column.uctoo_codelabs_algorithm.${key}`) }}
      </a-checkbox>
    </a-checkbox-group>
  </a-drawer>

  <a-form v-if="isIdsEmpty" ref="formRef" :model="formState" :rules="rules">
    <a-form-item v-if="selectedFormItems.includes('command_name')" :label="$t('database_column.uctoo.codelabs_algorithm.command_name')" name="command_name">
          <a-input v-model:value="formState.command_name" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('algorithm_code')" :label="$t('database_column.uctoo.codelabs_algorithm.algorithm_code')" name="algorithm_code">
          <a-input v-model:value="formState.algorithm_code" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('filename')" :label="$t('database_column.uctoo.codelabs_algorithm.filename')" name="filename">
          <a-input v-model:value="formState.filename" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('filepath')" :label="$t('database_column.uctoo.codelabs_algorithm.filepath')" name="filepath">
          <a-input v-model:value="formState.filepath" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('template_url')" :label="$t('database_column.uctoo.codelabs_algorithm.template_url')" name="template_url">
          <a-input v-model:value="formState.template_url" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('opensource')" :label="$t('database_column.uctoo.codelabs_algorithm.opensource')" name="opensource">
          <a-input v-model:value="formState.opensource" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('author')" :label="$t('database_column.uctoo.codelabs_algorithm.author')" name="author">
          <a-input v-model:value="formState.author" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('author_url')" :label="$t('database_column.uctoo.codelabs_algorithm.author_url')" name="author_url">
          <a-input v-model:value="formState.author_url" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('user_id')" :label="$t('database_column.uctoo.codelabs_algorithm.user_id')" name="user_id">
          <a-input v-model:value="formState.user_id" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('tags')" :label="$t('database_column.uctoo.codelabs_algorithm.tags')" name="tags">
          <a-input v-model:value="formState.tags" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('docs')" :label="$t('database_column.uctoo.codelabs_algorithm.docs')" name="docs">
          <a-input v-model:value="formState.docs" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('images')" :label="$t('database_column.uctoo.codelabs_algorithm.images')" name="images">
            <ImageUpload v-model="formState.images" :max-count="20" :upload-text="$t('page.image_upload')" />
          </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('description')" :label="$t('database_column.uctoo.codelabs_algorithm.description')" name="description">
          <a-input v-model:value="formState.description" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('price')" :label="$t('database_column.uctoo.codelabs_algorithm.price')" name="price">
          <a-input v-model:value="formState.price" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('status')" :label="$t('database_column.uctoo.codelabs_algorithm.status')" name="status">
          <a-input v-model:value="formState.status" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('arguments')" :label="$t('database_column.uctoo.codelabs_algorithm.arguments')" name="arguments">
          <a-input v-model:value="formState.arguments" />
        </a-form-item>
</a-form>

<!-- edit multi row -->
  <a-form v-else class="dynamic-form" ref="formRef" :model="formState">
    <a-form-item v-for="(field, index) in formFields" :key="index" class="form-row">
      <!-- 字段选择器 -->
      <a-space>
      <a-select 
        v-model="field.selectedField"
        :placeholder="$t('page.SelectField')"
        @change="(value:any) => handleFieldChange(index, value)"
        style="width: 160px"
      >
        <a-option 
          v-for="opt in getFieldOptions()" 
          :key="opt" 
          :value="opt"
        >
          {{ opt }}
        </a-option>
      </a-select>

      <!-- 动态输入组件：直接绑定到 field -->
      <a-input
        :id="`input-${index}`"
        v-if="field.selectedField && isNumberField(field.selectedField)"
        v-model.number="field.inputValue"
        type="number"
      />
      <a-input
        :id="`input-${index}`"
        v-else
        v-model="field.inputValue"
      />
      <a-button 
        v-if="index > 0" 
        @click="removeField(index)"
        type="danger"
      >
      <template #icon><VbenIcon icon="ant-design:minus-circle-outlined" /></template>
      </a-button>
      </a-space>
    </a-form-item>
  
    <a-button @click="addField" type="danger">
      <template #icon><VbenIcon icon="ant-design:plus-circle-outlined" /></template>
    </a-button>
  </a-form>
  </a-modal>
</template>
